package com.changan.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.*;

/**
 * @program: alipay
 * @description: 支付接口
 * @author: Mr.Nie
 * @create: 2021-12-15 22:13
 **/
public class PayController {

    private final String APP_ID = "2016092500596842";
    private final String APP_PRIVATE_KEY = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQClKNF8psCdkuNUoN/GhMXOpCeOcvhnNJ9JV2F1iXza88ebfHmtbEY8FyzereWuddV5Q9WFREyFyISDzX63i5HIW42Bu9e9n3I6U/E2UYaRw5MHTZ9qAUz3y/1uw6/6ViX3Rwd5Rwl0KklWIpKFeqFcNwk6vgLPyrU7poUdMybO0P7ufFiLS89/hO8NzGWbenakh05cLomd9tlrlrYAhp1y7hYu80XB1k6p2E8+ufwUJ/LerZOIpFWenPbGZFsIuIz8NWWb3G3Ejcc7kL1bOj5lzz/CSukYnvgXMmiDStT6QNgat+jnOVQ87I6wFoqZfDYQ63V+pfj4fyp8y8+WYGPbAgMBAAECggEAMYW6wtixWs5HkgGm97yqH1sDbWg16aRSusgTtg2ivXhpesrpJUIZET2Vu7OC8jvs5a6cYJhpJZhJe8frXhfgf6ZMGQF9ICOmOa0f37y0UBLHjGIPEdcQACFPfZ35r2OTgMDwkcHmKMnhMY2uR43MwnzSLKX669mJXDiDI41J7qsqgEw7EXXjQOc8bZsEYdVe+OOctjQ3iI/AOhIhU2TltN2DqgHqlkrkkKSM1Ut36i7p0SspJAw///oQ65e3g8z7FYjClZPikqk9398bMDrNA93t2hP2XLi0BJIWgf/qRf6Ephobnd9Q4+dbM1pHnAM6tqgFxI4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MuIVq69qYFgpE4219H3e0sGQzXalx9SfvMeazItTJXh7obcETUwQ0F8U4DAFVYEooFjD1VnNiDtsKrJwHzqE7bz7NFR3k/Zz8ksT3boCzOoUANzfQohn5WyclgoLKBwkZRQzzEuHYStkyKJbryYptXwGo9iSJ5JcIqrlk87HJPcmbRPKJrxFg4rE3bZbJ+AYejcLYPmyz5/owWEp1xpc7HvfklU2EzfJhJxNkNSoSKRZcBRTXZQsA7hTi7YmjZeNslk62OeA5wIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://127.0.0.1/notifyUrl";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://127.0.0.1/returnUrl";



    @RequestMapping("aliapy")
    public void alipay(HttpServletResponse httpResponse) throws IOException {

        SecureRandom r= new SecureRandom();
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        String out_trade_no = UUID.randomUUID().toString();
        //付款金额，必填
        String total_amount =Integer.toString(r.nextInt(9999999)+1000000);
        //订单名称，必填
        String subject ="奥迪A8 2021款 A8L 60 TFSl quattro豪华型";
        //商品描述，可空
        String body = "尊敬的会员欢迎购买奥迪A8 2021款 A8L 60 TFSl quattro豪华型";
        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    @RequestMapping(value = "/returnUrl", method = RequestMethod.GET)
    public String returnUrl(HttpServletRequest request, HttpServletResponse response)
            throws IOException, AlipayApiException {
        System.out.println("=================================同步回调=====================================");

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println(params);//查看参数都有哪些
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
        //验证签名通过
        if(signVerified){
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            System.out.println("商户订单号="+out_trade_no);
            System.out.println("支付宝交易号="+trade_no);
            System.out.println("付款金额="+total_amount);

            //支付成功，修复支付状态
            payService.updateById(Integer.valueOf(out_trade_no));
            return "ok";//跳转付款成功页面
        }else{
            return "no";//跳转付款失败页面
        }

    }


}
